import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
typedef SearchItemCall = void Function(String item);

class SearchBarDelegate extends SearchDelegate<String> {
  Widget temp;
  Widget body=Center(
    child: Text("加载中"),
  );
  @override
  List<Widget> buildActions(BuildContext context) {
    //右侧显示内容 这里放清除按钮
    return [
      IconButton(
        icon: Icon(Icons.menu),
        onPressed: () {
          query = "";
          showSuggestions(context);
        },
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    //左侧显示内容 这里放了返回按钮
    return IconButton(
      icon: AnimatedIcon(
          icon: AnimatedIcons.menu_arrow, progress: transitionAnimation),
      onPressed: () {
        if (query.isEmpty) {
          close(context, null);
        } else {
          query = "";

          showSuggestions(context);
        }
      },
    );
  }

  @override
  Widget buildResults(BuildContext context){
    //点击了搜索显示的页面
     // Toast.show("网络请求中", context, duration: Toast.LENGTH_SHORT);
    return ResultView(query);

  }
  void setquery(String s)
  {
    query=s;
  }
  @override
  Widget buildSuggestions(BuildContext context) {
    //点击了搜索窗显示的页面
    return SearchContentView();
  }

  @override
  ThemeData appBarTheme(BuildContext context) {
    return super.appBarTheme(context);
  }
}
class ResultView extends StatefulWidget{
  var question;
  @override
   createState() =>ResultViewState(question);

  ResultView(String question){this.question=question;debugPrint("is in resultview "+question);createState();}
}
class ResultViewState extends State<ResultView>{
   var question;
  ResultViewState(String question){
    debugPrint(question);
    this.question=question;
    initState();
    build(context);
  }
  Widget body=Center(
    child: Column(
      children: <Widget>[Material(
    type: MaterialType.transparency,
      child: new Center(
        child: new SizedBox(
          width: 120.0,
          height: 120.0,
          child: new Container(
            decoration: ShapeDecoration(
              color: Colors.grey,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(
                  Radius.circular(8.0),
                ),
              ),
            ),
            child: new Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                new CircularProgressIndicator(),
                new Padding(
                  padding: const EdgeInsets.only(
                    top: 20.0,
                  ),
                  child: new Text("敌军还有十秒到达战场",
                      style: TextStyle(
                      color: Colors.black)
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    ),
      ],
    )

  ),temp;
  Response response;
  Future<Response> getData() async{
    Dio dio = Dio();
    try{
      response =
      await dio.get("https://sduonline.cn/isduapp_main/library/search?name="+question) ;

    } on Error catch (e){
      debugPrint(e.toString());
    }
    return response;
  }

  @override
  void initState() {
    super.initState();
    getData().whenComplete((){
      var _data;
      try{
        _data = JsonDecoder().convert(response.toString());
      }catch(e){
        debugPrint(e.toString());
      }
      finally{
       // debugPrint(response.toString());
      }
      debugPrint(_data["status"].toString());
      if (_data["status"] != "success")
        body = Center(child: Text("未查询到相关图书"),);
      else {
        List _obj = _data["obj"];
         temp = SingleChildScrollView(
            child: Center(
                child: Column(
                    children:
                    _obj
                        .map(
                            (e) =>
                            SizedBox(
                              height: 150.0,
                              width: 250,
                              child:
                              Card(color: Colors.white70,
                                  elevation: 15.0,
                                  shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(14.0))),
                                  child: new Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text("书名： "+e["name"],
                                        style:TextStyle(
                                          decoration: TextDecoration.underline,
                                          fontStyle: FontStyle.normal,
                                          //letterSpacing: 10.0,
                                          fontSize: 15,
                                          fontWeight: FontWeight.w700,
                                        ),
                                      ),
                                      Text("编码:  "+e["code"]),
                                      Text("作者:"  +e["author"])
                                    ],
                                  )
                              ),
                            )
                    )
                        .toList())));
        setState(() {
          body=temp;
        });
      }
    });

  }

  @override
  Widget build(BuildContext context) {
    return body;
  }
}
class SearchContentView extends StatefulWidget {
  @override
  _SearchContentViewState createState() => _SearchContentViewState();
}

class _SearchContentViewState extends State<SearchContentView> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            child: Text(
              '大家都在搜',
              style: TextStyle(fontSize: 16),
            ),
          ),
          SearchItemView(),
          Container(
            margin: EdgeInsets.only(top: 20),
            child: Text(
              '历史记录',
              style: TextStyle(fontSize: 16),
            ),
          ),
          SearchItemView()
        ],
      ),
    );
  }
}

class SearchItemView extends StatefulWidget {
@override
_SearchItemViewState createState() => _SearchItemViewState();
}

class _SearchItemViewState extends State<SearchItemView> {
  List<String> items = [
    '计算机网络',
    'Linux基层原理',
    'java从零开始',
    '软件工程',
    'Windows操作',
    'HTML5',
    '网络安全',
    'ios编程',
    'js'
  ];
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Wrap(
        spacing: 10,
        // runSpacing: 0,
        children: items.map((item) {
          return SearchItem(title: item);
        }).toList(),
      ),
    );
  }
}

class SearchItem extends StatefulWidget {
  @required
  final String title;
  const SearchItem({Key key, this.title}) : super(key: key);
  @override
  _SearchItemState createState() => _SearchItemState();
}

class _SearchItemState extends State<SearchItem> {
  var question;
  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        child: Chip(
          label: Text(widget.title),
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10)
          ),
        ),
        onTap: () {
        },
      ),
      color: Colors.white,
    );
  }
}